/**
 * Created by Amaris on 2016/12/6.
 */

var async = require('async');
var util = require('../utils/util.js');
var surveyingClass = require('../class/surveying.js');
var userjoinCtrl = require('../controller/controller.userjoin.js');

module.exports = {

    create: function (params, cb) {
        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var surveying = new surveyingClass();

        var checkResult = surveying.checkParams(
            [
                'seller',
                'industry',
                'startTime',
                'finishTime',
                'type',
                'range',
                'createUid'
            ],
            params);
        if (checkResult) {
            cb(null, util.getErrorRes('400', checkResult));
            return;
        } else {
            surveying.init(params);
        }

        models.surveying.create(surveying.getParams(), function (err, data) {
            if (err || !data) {
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }

            cb(null, util.getSuccessRes(data));
        });
    },


    update: function (params, cb) {
        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var surveying = new surveyingClass();
        var checkResult = surveying.checkParams(['rowId'], params);
        var checkScore = surveying.checkParams(['score'], params);

        if (checkResult) {
            cb(null, util.getErrorRes('400', checkResult));
            return;
        } else {

            if (!checkScore) {

                var now = new Date();
                var jsonDate = now.toJSON();
                var then = new Date(jsonDate);
                params.scoreTime = then;
            }

            surveying.init(params);
        }

        models.surveying.update({rowId: params.rowId}, surveying.getParams()).exec(function (err, data) {
            if (err || !data) {
                console.log(err);
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }
            cb(null, util.getSuccessRes(data));
        });
    },
    getInfo: function (params, cb) {
        var models = util.models;

        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var surveying = new surveyingClass();

        var checkResult = surveying.checkParams(['rowId'], params);
        if (checkResult) {
            cb(null, util.getErrorRes('400', checkResult));
            return;
        } else {
            surveying.init(params);
        }


        async.series({

            surveyingInfo: function (callback) {
                models.surveying.findOne(surveying.getParams()).populate('seller').populate('createUid').populate('scoreUid').populate('industry').populate('company').exec(function (err, data) {

                    if (err || !data) {
                        cb(err, null);
                        return;
                    }
                    callback(null, data);

                });
            },
            userjoinList: function (callback) {
                if (params.rowId) {
                    userjoinCtrl.getUserJoinListByActionId({
                        actionId: params.rowId
                    }, function (err, result) {

                        if (err) {
                            callback(null, err);
                        } else {
                            callback(null, result.obj);
                        }
                    });
                } else {
                    callback(null, null);
                }

            },
            userjoinInfo: function (callback) {
                if (params.userId) {
                    userjoinCtrl.getUserJoinInfoByUserIdActionId({
                        actionId: params.rowId,
                        userId: params.userId
                    }, function (err, result) {

                        if (err) {
                            callback(null, err);
                        } else {
                            callback(null, result.obj);
                        }
                    });
                } else {
                    callback(null, null);
                }
            },
        }, function (err, results) {
            if (err) {
                cb(null, null);
            } else {
                if (results.surveyingInfo) {

                    results.surveyingInfo.userjoinInfo = results.userjoinInfo;
                    results.surveyingInfo.userjoinList = results.userjoinList;

                }
                cb(null, util.getSuccessRes(results.surveyingInfo));
            }
        });


    },
    getList: function (params, cb) {

        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = "数据库连接失败";
            cb(err, null);
            return;
        }
        var surveying = new surveyingClass();

        var checkResult = surveying.checkParams(['createUid'], params);
        var expr = {};

        if (!checkResult) {
            surveying.init(params);
            var checkTime = surveying.checkParams(['startTime', 'finishTime'], params);
            if (checkTime) {
                expr = {

                    createUid: surveying.getParam('createUid'),
                    teamId: surveying.getParam('teamId')
                }
            } else {
                expr = {
                    or: [
                        {
                            startTime: {
                                '>=': new Date(surveying.getParam('startTime')),
                                '<=': new Date(surveying.getParam('finishTime'))
                            }
                        }, {
                            finishTime: {
                                '>=': new Date(surveying.getParam('startTime')),
                                '<=': new Date(surveying.getParam('finishTime'))
                            }
                        }, {
                            startTime: {
                                '<=': new Date(surveying.getParam('startTime')),

                            },
                            finishTime: {
                                '>=': new Date(surveying.getParam('finishTime'))
                            }
                        }
                    ],

                    teamId: surveying.getParam('teamId'),
                    createUid: surveying.getParam('createUid')
                }
            }

        } else {
            surveying.init(params);

            var checkTime = surveying.checkParams(['startTime', 'finishTime'], params);
            if (!checkTime) {
                expr = {
                    or: [
                        {
                            startTime: {
                                '>': new Date(surveying.getParam('startTime')),
                                '<': new Date(surveying.getParam('finishTime'))
                            }
                        }, {
                            finishTime: {
                                '>': new Date(surveying.getParam('startTime')),
                                '<': new Date(surveying.getParam('finishTime'))
                            }
                        }, {
                            startTime: {
                                '<=': new Date(surveying.getParam('startTime')),

                            },
                            finishTime: {
                                '>=': new Date(surveying.getParam('finishTime'))
                            }
                        }
                    ],
                    teamId: surveying.getParam('teamId')
                }
            }
        }
        var checkSeller = surveying.checkParams(['seller'], params);
        if(!checkSeller){
            expr.seller=surveying.getParam('seller');
        }

        models.surveying.find(expr).populate('seller').populate('createUid').populate('industry').exec(function (err, data) {

            if (err || !data) {
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }
            cb(null, util.getSuccessRes(data));
        });
    },

    /**
     * 根据Ids获取调研列表
     * @param params
     * @param cb
     */
    getListByIds: function (params, cb) {

        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = "数据库连接失败";
            cb(err, null);
            return;
        }
        var surveying = new surveyingClass();

        var checkResult = surveying.checkParams(['createUid'], params);
        var expr = {};

        if (!checkResult) {
            surveying.init(params);
            var checkTime = surveying.checkParams(['startTime', 'finishTime'], params);
            if (checkTime) {
                expr = {

                    createUid: surveying.getParam('createUid'),
                    rowId: params.rowIdArr

                }
            } else {
                expr = {
                    or: [
                        {
                            startTime: {
                                '>=': new Date(surveying.getParam('startTime')),
                                '<=': new Date(surveying.getParam('finishTime'))
                            }
                        }, {
                            finishTime: {
                                '>=': new Date(surveying.getParam('startTime')),
                                '<=': new Date(surveying.getParam('finishTime'))
                            }
                        }, {
                            startTime: {
                                '<=': new Date(surveying.getParam('startTime')),

                            },
                            finishTime: {
                                '>=': new Date(surveying.getParam('finishTime'))
                            }
                        }
                    ],


                    createUid: surveying.getParam('createUid'),
                    rowId:  params.rowIdArr

                }
            }

        } else {
            surveying.init(params);

            var checkTime = surveying.checkParams(['startTime', 'finishTime'], params);
            if (!checkTime) {
                expr = {
                    or: [
                        {
                            startTime: {
                                '>=': new Date(surveying.getParam('startTime')),
                                '<=': new Date(surveying.getParam('finishTime'))
                            }
                        }, {
                            finishTime: {
                                '>=': new Date(surveying.getParam('startTime')),
                                '<=': new Date(surveying.getParam('finishTime'))
                            }
                        }, {
                            startTime: {
                                '<=': new Date(surveying.getParam('startTime')),

                            },
                            finishTime: {
                                '>=': new Date(surveying.getParam('finishTime'))
                            }
                        }
                    ],
                    rowId:  params.rowIdArr
                }
            }
        }

        models.surveying.find(expr).populate('seller').populate('createUid').populate('industry').exec(function (err, data) {

            if (err || !data) {
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }
            cb(null, util.getSuccessRes(data));
        });
    },
    /**
     *根据teamId获取列表
     * @param params
     * @param cb
     */
    getListByTeamId: function (params, cb) {

        //console.log(params);

        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = "数据库连接失败";
            cb(err, null);
            return;
        }
        var surveying = new surveyingClass();

        var checkResult = surveying.checkParams(['teamId'], params);
        if (checkResult) {
            cb(null, util.getErrorRes('400', checkResult));
            return;
        } else {
            surveying.init(params);
        }
        models.surveying.find(surveying.getParams()).populate('seller').populate('createUid').populate('industry').exec(function (err, data) {

            if (err || !data) {
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }

            cb(null, util.getSuccessRes(data));
        });
    },

    /**
     *根据sellerId获取列表
     * @param params
     * @param cb
     */
    getListBySeller: function (params, cb) {

        //console.log(params);

        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = "数据库连接失败";
            cb(err, null);
            return;
        }
        var surveying = new surveyingClass();

        var checkResult = surveying.checkParams(['seller'], params);
        if (checkResult) {
            cb(null, util.getErrorRes('400', checkResult));
            return;
        } else {
            surveying.init(params);
        }
        models.surveying.find(surveying.getParams()).populate('seller').populate('createUid').populate('industry').exec(function (err, data) {

            if (err || !data) {
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }

            cb(null, util.getSuccessRes(data));
        });
    },

    delete: function (params, cb) {
        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var surveying = new surveyingClass();

        var checkResult = surveying.checkParams(['rowId'], params);
        if (checkResult) {
            cb(null, util.getErrorRes('400', checkResult));
            return;
        } else {
            surveying.init(params);
        }

        var rowId = params.rowId;
        models.surveying.destroy({'rowId': rowId}).exec(function (err, data) {
            if (err || !data) {
                cb(err, null);
                return;
            }
            if (data && data.length == 0) {
                var err = new Error();
                err.status = 500;
                err.message = '删除失败';
                cb(err, null);
                return;
            }
            cb(null, util.getSuccessRes(data));
        });
    }

};



